import React, { Component } from 'react';
import {connect} from 'react-redux';

import {Route, Redirect} from 'react-router-dom';
import {setLogin} from '@/store/actions';
import fetchJson from '@/utils/fetch';
import Login from '@/pages/Login';
import Banner from '@/pages/Banner';
import Car from '@/pages/Car';
import Tabs from '@/components/Tabs';

class App extends Component {
  constructor (...args) {
    super(...args);
    this.state = {
      show: true,
      curTab: 0
    };
    this.tabs = [
      {text: '横幅管理', path: '/'},
      {text: '车辆管理', path: '/car'}
    ];
  }
  async componentDidUpdate () {
    await this.checkLogin();
  }
  async componentDidMount () {
    // 判断是否已经登录
    // if (localStorage.login) {
    //   this.props.setLogin(true);
    //   this.props.history.push('/');
    // }
    console.log(this.props)
    await this.checkLogin();
    // 判断tab的网址
    this.tabs.forEach((item, index) => {
      if (item.path === this.props.location.pathname) {
        this.setState({curTab: index});
      }
    })
  }
  async checkLogin () {
    if (this.props.location.pathname !== '/login' && !this.props.admin.login) {
      try {
        await fetchJson('admin/checklogin')
        this.props.setLogin(true);
      } catch (e) {
        console.error(e);
        this.props.history.push('/login', {});
      }
    }
  }
  // 切换tabs
  switchTab (index) {
    console.log(index);
    this.setState({
      curTab: index
    });
  }
  render() {
    return (
      <div>
        {
          this.props.admin.login ? (
            <Tabs
              cur={this.state.curTab}
              tabs={this.tabs}
              switchTab={this.switchTab.bind(this)}
            ></Tabs>
          ) : ''
        }
        <Route path="/" exact component={Banner}></Route>
        <Route path="/login" component={Login}></Route>
        <Route path="/car" component={Car}></Route>
      </div>
    );
  }

}

export default connect((state, props) => Object.assign({}, props, state), {
  setLogin
})(App);
